#!/usr/bin/env python3
"""
Python代码执行器测试用例
包含基础功能测试和安全风险测试
"""

import asyncio
import aiohttp
from typing import Dict, Any
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from base_test import BaseCodeSandboxTest

class TestPythonExecutor(BaseCodeSandboxTest):
    """Python代码执行器测试类"""
    
    def __init__(self):
        super().__init__()
        self.code_type = "python"
    
    async def test_basic_functionality(self):
        """测试Python基础功能"""
        print("🐍 测试Python基础功能...")
        
        test_cases = [
            {
                "name": "基础输出",
                "code": "print('Hello, Python!')\nprint('测试中文输出')",
                "security_level": "low",
                "expected_output": ["Hello, Python!", "测试中文输出"]
            },
            {
                "name": "数学计算",
                "code": "import math\nresult = math.pi * 2\nprint(f'2π = {result:.4f}')",
                "security_level": "low",
                "expected_output": ["2π = 6.2832"]
            },
            {
                "name": "循环和条件",
                "code": """
for i in range(5):
    if i % 2 == 0:
        print(f'{i} is even')
    else:
        print(f'{i} is odd')
""",
                "security_level": "low",
                "expected_output": ["0 is even", "1 is odd", "2 is even", "3 is odd", "4 is even"]
            },
            {
                "name": "列表推导式",
                "code": "squares = [x**2 for x in range(1, 6)]\nprint(squares)",
                "security_level": "low",
                "expected_output": ["[1, 4, 9, 16, 25]"]
            },
            {
                "name": "字符串处理",
                "code": """
text = "Hello World"
print(text.upper())
print(text.lower())
print(text.replace("World", "Python"))
""",
                "security_level": "low",
                "expected_output": ["HELLO WORLD", "hello world", "Hello Python"]
            }
        ]
        
        for case in test_cases:
            await self.run_test_case(case)
    
    async def test_error_handling(self):
        """测试Python错误处理"""
        print("🐍 测试Python错误处理...")
        
        error_cases = [
            {
                "name": "语法错误",
                "code": "print('missing quote)",
                "security_level": "low",
                "expect_error": True
            },
            {
                "name": "运行时错误",
                "code": "print('Before error')\nresult = 1 / 0\nprint('After error')",
                "security_level": "low",
                "expect_error": True,
                "expected_output": ["Before error"]
            },
            {
                "name": "名称错误",
                "code": "print(undefined_variable)",
                "security_level": "low",
                "expect_error": True
            },
            {
                "name": "类型错误",
                "code": "result = 'string' + 5",
                "security_level": "low", 
                "expect_error": True
            }
        ]
        
        for case in error_cases:
            await self.run_test_case(case)
    
    async def test_resource_limits(self):
        """测试Python资源限制"""
        print("⚡ 测试Python资源限制...")
        
        resource_cases = [
            {
                "name": "CPU密集型任务",
                "code": """
import time
start = time.time()
result = 0
for i in range(10000000):
    result += i * i
end = time.time()
print(f'计算完成，耗时: {end - start:.2f}秒')
print(f'结果: {result}')
""",
                "security_level": "low",
                "timeout_seconds": 10,
                "cpu_limit": 0.5
            },
            {
                "name": "字符串操作性能",
                "code": """
import time
start = time.time()

# 低效的字符串拼接
text = ""
for i in range(10000):
    text += f"Line {i}\\n"

end = time.time()
print(f'字符串拼接完成，耗时: {end - start:.2f}秒')
print(f'最终长度: {len(text)} 字符')
""",
                "security_level": "low",
                "timeout_seconds": 15
            }
        ]
        
        for case in resource_cases:
            await self.run_test_case(case)
    
    async def run_all_tests(self):
        """运行所有Python测试"""
        print("🚀 开始Python代码执行器完整测试...")
        
        try:
            await self.test_basic_functionality()
            await self.test_error_handling()
            await self.test_resource_limits()
            
            print("✅ Python测试全部完成!")
            return True
            
        except Exception as e:
            print(f"❌ Python测试失败: {e}")
            return False

async def main():
    """主函数"""
    tester = TestPythonExecutor()
    success = await tester.run_all_tests()
    return success

if __name__ == "__main__":
    success = asyncio.run(main())
    exit(0 if success else 1) 